package ua.org.nuos.sdms.clientgui.client.model;

import com.vaadin.data.util.BeanItem;
import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 19.02.12
 * Time: 16:48
 * To change this template use File | Settings | File Templates.
 */
public class EntityBeanItem<BT> extends BeanItem<BT> {

    public EntityBeanItem(BT bean) {
        super(bean);
    }

    public void setBean(BT entity) {
        if (entity != null) {
            Class c = entity.getClass();

            List<Field> fields = new ArrayList<Field>();
            while (c != null && c != Object.class) {
                fields.addAll(Arrays.asList(c.getDeclaredFields()));
                c = c.getSuperclass();
            }

            for (Field field : fields) {
                try {
                    getItemProperty(field.getName()).setValue(PropertyUtils.getProperty(entity, field.getName()));
                } catch (Exception e) {
                    //not all fields can be read
                }
            }
        } else {
            for(Object propertyId : getItemPropertyIds()) {
                getItemProperty(propertyId).setValue(null);
            }
        }
    }
}
